<?php
namespace App\Models\Tools;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class Message extends Model
{
    /**
     * 发送短信验证码
     * @param $phone string 手机号
     * @param $code int 验证码
     * @return bool
     */
    public static function sendVerifyCode($phone, $code)
    {
        $url = env("SMS_URL");
        $post_data = [
            'account' => env("SMS_ACCOUNT"),
            'password' => env("SMS_PASSWORD"),
            'msg' => '【'.env("SMS_SIGNATURE").'】验证码' . $code . '，3分钟内有效，请勿向他人泄漏。欢迎加入来飞网！',
            'phone' => $phone,
        ];
        $result = self::send_post($url, $post_data);
        if($result['code'] == 0){
            return true;
        } else {
            Log::info('发送短信失败',['request'=>$post_data, 'response'=>$result]);
            return false;
        }
    }

    public static function exploreRemind($phone)
    {
        $url = env("SMS_URL");
        $post_data = [
            'account' => env("SMS_ACCOUNT"),
            'password' => env("SMS_PASSWORD"),
            'msg' => '【'.env("SMS_SIGNATURE").'】您有点评任务尚未提交，请在接单后48小时内提交投稿。如果超时，系统将会自动撤回订单！如有疑问，请联系来飞网公众号在线客服。',
            'phone' => $phone,
        ];
        $result = self::send_post($url, $post_data);
        if($result['code'] == 0){
            return true;
        } else {
            Log::info('发送短信失败',['request'=>$post_data, 'response'=>$result]);
            return false;
        }
    }

    /**
     * 发送中奖信息通知
     * @param string|int $phone
     * @param string $goods_name
     * @return bool
     */
    public static function lotteryWin($phone, $goods_name)
    {
        $url = env("SMS_URL");
        if(mb_strlen($goods_name) > 18){
            $goods_name = mb_substr($goods_name,0,15) . '...';
        }
        $post_data = [
            'account' => env("SMS_ACCOUNT"),
            'password' => env("SMS_PASSWORD"),
            'msg' => '【'.env("SMS_SIGNATURE").'】您参与的霸王餐活动【'.$goods_name.'】已中奖，请在3小时内进入来飞网公众号领取奖品，过期失效！如有疑问，请联系来飞网公众号在线客服。',
            'phone' => $phone,
        ];
        $result = self::send_post($url, $post_data);
        if($result['code'] == 0){
            return true;
        } else {
            Log::info('发送短信失败',['request'=>$post_data, 'response'=>$result]);
            return false;
        }
    }

    /**
     * 发送json格式请求
     * @param $url string 请求地址
     * @param $post_data array 请求参数
     * @return array
     */
    public static function send_post($url, $post_data) {
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/json;charset=UTF-8',
                'content' => json_encode($post_data),
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result, true);
    }

}
